package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.property.PadUserAuthPushDTO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.POJO.VO.app.AppDoorDevicesVO;
import com.itlong.cloud.POJO.VO.app.AppFloorDevicesVO;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.app.service.IAppDeviceService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.PadChangeBusinessEnum;
import com.itlong.cloud.property.service.IPadFaceSyncDataService;
import com.itlong.cloud.property.service.IPropertyEquipService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * <desc>
 *      平板用户权限信息变更指令推送消费者
 * </desc>
 */
@Component
public class PadUserAuthChangePushConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(PadUserAuthChangePushConsumer.class);

    @Autowired
    IAppDeviceService iAppDeviceService;

    @Autowired
    IPadFaceSyncDataService iPadFaceSyncDataService;


    @Autowired
    IPropertyEquipService iPropertyEquipService;

    /**
     * <desc>
     *      平板用户权限信息变更指令推送消费者
     * <desc/>
     *
     * @param   message 消息数据
     * @author JiaqiX
     * @createDate 2019/01/24
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_PAD_USER_AUTH_CHANGE_PUSH_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        //LOG.info("RabbitMQ_推送平板数据:" + new String(body));
        try {
            Thread.sleep(2000);
            TimeTaskDeadMessageQueuePO deadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            JSONObject jsdata = JSONObject.parseObject(deadMessageQueuePO.getMessageContent());
            List<PadUserAuthPushDTO> dtos = JsonUtil.decode(jsdata.get("data").toString(), new TypeReference<List<PadUserAuthPushDTO>>() {});
            for(PadUserAuthPushDTO dto : dtos){
                if(dto.getPushType() == PadChangeBusinessEnum.PUSH_USER.getCommandType()){
                    List<Map<String,Object>> auths = new ArrayList<>();
                    Map<String, Object> auth = new HashMap<>();
                    //门禁
                    List<AppDoorDevicesVO> doors = iAppDeviceService.getDoorDevices(dto.getUserId(), dto.getProjectId(), 1);
                    List<Map<String,Object>> sysAuths = new ArrayList<>();
                    auth.put("userId",dto.getUserId());
                    auth.put("deviceType",1);
                    auth.put("houseUserType","5");
                    auth.put("startTime","");
                    auth.put("endTime","");
                    for(AppDoorDevicesVO door : doors){
                        Map<String,Object> sysAuth = new HashMap<>();
                        sysAuth.put("auth","8");
                        sysAuth.put("deviceUnique",door.getDeviceUnique());

                        //1获取当前设备的所在 地址
                        List<Map> untilMap = iAppDeviceService.getDeviceEntranceBridgeInfoByDeviceUnique(door.getDeviceUnique());

                        //获取当前地址下的电梯集合
                        Set<String> set = new HashSet<>();
                        for (Map<String, Object> map : untilMap) {
                            List<CloudElevatorVO>    DeviceUniques = iPropertyEquipService.getElevatorListByAddress(map);
                            for (CloudElevatorVO deviceUnique : DeviceUniques) {
                                set.add(deviceUnique.getDeviceUnique());
                            }
                        }



                        Map commonFloorMap=null;
                        Map publicFloorMap=null;
                        if (door.getCommonFloor()!=null){
                            commonFloorMap = JSON.parseObject(door.getCommonFloor());
                          ///  commonFloorMap.put(door.getDeviceUnique(), "x".equals(commonFloorMap.get(door.getDeviceUnique()))?"":commonFloorMap.get(door.getDeviceUnique()));
                        }
                        if (door.getPublicFloor()!=null){
                            publicFloorMap = JSON.parseObject(door.getPublicFloor());
                         //   publicFloorMap.put(door.getDeviceUnique(), "x".equals(publicFloorMap.get(door.getDeviceUnique()))?"":publicFloorMap.get(door.getDeviceUnique()));
                        }

                        if (set.size()==0){
                            sysAuth.put("commonFloor","");
                            sysAuth.put("publicFloor","");
                        }else {
                            for (String deviceUnique : set) {
                                if(commonFloorMap==null){
                                    sysAuth.put("commonFloor","");
                                }else if (commonFloorMap.containsKey(deviceUnique)) {
                                    sysAuth.put("commonFloor", (commonFloorMap == null || "x".equals(commonFloorMap.get(deviceUnique)))? "" : commonFloorMap.get(deviceUnique));
                                }
                                if(publicFloorMap==null){
                                    sysAuth.put("publicFloor","");
                                }else if (publicFloorMap.containsKey(deviceUnique)) {
                                    sysAuth.put("publicFloor", (publicFloorMap == null || "x".equals(publicFloorMap.get(deviceUnique))) ? "" : publicFloorMap.get(deviceUnique));
                                }
                            }
                        }
                        //sysAuth.put("commonFloor",(commonFloorMap==null)?"":commonFloorMap.get(door.getDeviceUnique()));
                        //sysAuth.put("publicFloor",(publicFloorMap==null)?"":publicFloorMap.get(door.getDeviceUnique()));
                        sysAuths.add(sysAuth);
                    }
                    //电梯
                    List<AppFloorDevicesVO> floors = iAppDeviceService.getFloorDevices(dto.getUserId(),dto.getProjectId(), 1);
                    auth.put("userId",dto.getUserId());
                    auth.put("deviceType", 2);
                    auth.put("houseUserType","5");
                    auth.put("startTime","");
                    auth.put("endTime","");
                    for(AppFloorDevicesVO floor : floors){
                        Map<String,Object> sysAuth = new HashMap<>();

                        sysAuth.put("auth",floor.getLiveFloor());
                        sysAuth.put("deviceUnique",floor.getDeviceUnique());
                        Map commonFloorMap=null;
                        Map publicFloorMap=null;
                        if (floor.getUserCommonFloor()!=null){
                            commonFloorMap = JSON.parseObject(floor.getUserCommonFloor());
                            commonFloorMap.put(floor.getDeviceUnique(), "x".equals(commonFloorMap.get(floor.getDeviceUnique()))?"":commonFloorMap.get(floor.getDeviceUnique()));
                        }
                        if (floor.getPublicFloor()!=null){
                            publicFloorMap = JSON.parseObject(floor.getPublicFloor());
                            publicFloorMap.put(floor.getDeviceUnique(), "x".equals(publicFloorMap.get(floor.getDeviceUnique()))?"":publicFloorMap.get(floor.getDeviceUnique()));
                        }
                        sysAuth.put("deviceUnique", floor.getDeviceUnique());
                        sysAuth.put("commonFloor",(commonFloorMap!=null && commonFloorMap.containsKey(floor.getDeviceUnique()))?commonFloorMap.get(floor.getDeviceUnique()):"");
                        sysAuth.put("publicFloor",(publicFloorMap!=null && publicFloorMap.containsKey(floor.getDeviceUnique()))?publicFloorMap.get(floor.getDeviceUnique()):"");


                        sysAuths.add(sysAuth);
                    }
                    auth.put("sysAuths",sysAuths);
                    auths.add(auth);
                    iPadFaceSyncDataService.pushUserAuthChange(dto.getUserId(),dto.getRoomId(),auths,dto.getProjectId(),dto.getInstructionType(),dto.getSourceSystem());
                }else if(dto.getPushType() == PadChangeBusinessEnum.PUSH_FULL.getCommandType()){
                    iPadFaceSyncDataService.pushFull(dto.getDeviceUnique(),dto.getProjectId());
                }
            }
        } catch (Exception e) {
            LOG.error("【RabbitMQ_平板用户权限信息变更指令推送消费者】:处理异常", e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
